/*****屏幕推送*****/
<template>
  <!---->
  <div style="overflow:hidden;">
    <search-table
      v-if="poll === false"
      :columns="tab6TbTitle1"
      :data="tab6TbData"
      :total="tab6PageCount"
      :page.sync="currPage"
      :size.sync="currSize"
      :showSelectTag="false"
      selectKey="id"
      :selection.sync="selectSession"
      @queryFun="getConnectAllHistories"
    >
      <template slot="button-group">
        <div v-if="type == 2 || routename == 'awdContestDetail' || routename == 'opContestDetail'">
          <Select filterable
            v-model="accessGroupId"
            style="width:150px;margin-right:15px;"
            @on-change="changeTeam"
            transfer
            clearable
            placeholder="请选择团队"
          >
            <Option
              v-for="item in searchMemberlist"
              :value="item.id"
              :key="item.id"
              :title="item.name"
              >{{ item.name }}</Option
            >
          </Select>
          <DatePicker
            :editable="false"
            type="datetime"
            :value="connectTime"
            format="yyyy-MM-dd HH:mm:ss"
            placement="bottom-start"
            style="width:170px;margin-right:15px;"
            confirm
            ref="datePicker"
            placeholder="选择连接时间"
            transfer
            @on-ok="clickOkBtn"
            @on-clear="clickClearBtn"
            @on-change="changeDates"
          ></DatePicker>
          <DatePicker
            :editable="false"
            type="datetime"
            :value="disconnectTime"
            format="yyyy-MM-dd HH:mm:ss"
            placement="bottom-start"
            style="width:170px;margin-right:15px;"
            confirm
            ref="datePicker"
            placeholder="选择断开时间"
            transfer
            @on-ok="clickOkDisconnect"
            @on-clear="clickClearDisconnect"
            @on-change="changeDisconnect"
          ></DatePicker>
        </div>
        <Button
          @click="reportScreenRecording"
          :disabled="selectSession.length == 0"
          v-if="isReportButton"
          >录屏上报</Button
        >
        <template v-if="hasData">
          <Button
            @click="sessionTranscoding"
            v-if="poll === false"
            :disabled="['success', 'transcoding'].includes(transcodingStatus)"
            >录屏转码</Button
          >
          <div class="flex">
            转码状态：<span :style="{ color: filterTranscodingStatus(transcodingStatus).color }">{{
              filterTranscodingStatus(transcodingStatus).txt
            }}</span>
          </div>
        </template>
      </template>
    </search-table>
    <Tabs v-model="tabName" v-else>
      <TabPane label="实时录屏" name="name1">
        <!-- <Row style="margin:16px 0;"> -->
        <search-table
          :columns="tab6TbTitle"
          :data="tab6TbData"
          :total="tab6PageCount"
          :page.sync="currPage"
          :size.sync="currSize"
          @queryFun="getConnectAllHistories"
        >
          <template slot="select-group"> </template>
        </search-table>
        <!--<Row type="flex" style="margin:15px 0">
						<Col>
						<Checkbox v-model="tab6move" style="font-size: 18px;">定位目标机器</Checkbox>
						<font size="3px">/ 推送的机器:</font>
						<Tag type="border" color="normal" v-model="vms4RedBlue" v-for="(vm,index) in vms4RedBlue" :key="index" @on-close="handleClose(vm)">{{vm.userName}}
						</Tag>
						</Col>
					</Row>-->
        <!-- <Page :total="tab6PageCount" show-elevator show-total @on-change="tab6Change" style="float:right;" v-show="tab6TbData.length > 0" /> -->
        <!-- </Row> -->
        <!--<Table stripe :columns="tab6TbTitle" :data="tab6TbData"></Table>-->
        <!-- <card-list :columns="tab6TbTitle" :data="tab6TbData"></card-list> -->
        <!-- <TableList :columns="tab6TbTitle" :data="tab6TbData"></TableList> -->
      </TabPane>
      <!-- poll 赛前 赛后   -->
      <!-- 赛后只有录屏回放 -->
      <TabPane label="录屏回放" name="name2">
        <search-table
          :columns="tab6TbTitle1"
          :data="tab6TbData"
          :total="tab6PageCount"
          :page.sync="currPage"
          :size.sync="currSize"
          :showSelectTag="false"
          selectKey="id"
          :selection.sync="selectSession"
          @queryFun="getConnectAllHistories"
        >
          <template slot="button-group">
            <Button
              @click="reportScreenRecording"
              :disabled="selectSession.length == 0"
              v-if="isReportButton"
              >录屏上报</Button
            >
            <Button
              @click="sessionTranscoding"
              v-if="tabName === 'name2' && poll === false"
              :disabled="['success', 'transcoding'].includes(transcodingStatus)"
              >录屏转码</Button
            >
          </template>

          <template slot="select-group" v-if="[1, 9].includes(type)">
            <Select filterable
              v-model="accessGroupId"
              style="width:150px;margin-right:15px;"
              @on-change="changeTeam"
              transfer
              clearable
              placeholder="请选择团队"
            >
              <Option
                v-for="item in searchMemberlist"
                :value="item.id"
                :key="item.id"
                :title="item.name"
                >{{ item.name }}</Option
              >
            </Select>
            <DatePicker
              :editable="false"
              type="datetime"
              :value="connectTime"
              format="yyyy-MM-dd HH:mm:ss"
              placement="bottom-start"
              style="width:170px;margin-right:15px;"
              confirm
              ref="datePicker"
              placeholder="选择连接时间"
              transfer
              @on-ok="clickOkBtn"
              @on-clear="clickClearBtn"
              @on-change="changeDates"
            ></DatePicker>
            <DatePicker
              :editable="false"
              type="datetime"
              :value="disconnectTime"
              format="yyyy-MM-dd HH:mm:ss"
              placement="bottom-start"
              style="width:170px;margin-right:15px;"
              confirm
              ref="datePicker"
              placeholder="选择断开时间"
              transfer
              @on-ok="clickOkDisconnect"
              @on-clear="clickClearDisconnect"
              @on-change="changeDisconnect"
            ></DatePicker>
          </template>
          <!-- 转码状态：{{transcodingStatus === 'failed' ? '失败' : transcodingStatus === 'success' ? '成功' : '进行中' }} -->
        </search-table>
        <!-- <Row style="margin:16px 0;">
					<Page :total="tab6PageCount" show-total show-elevator @on-change="tab6Change" style="float:right;" v-show="tab6TbData.length > 0" />
				</Row> -->
        <!--<Table stripe :columns="tab6TbTitle" :data="tab6TbData"></Table>-->
        <!-- <TableList :columns="tab6TbTitle1" :data="tab6TbData"></TableList> -->
      </TabPane>
    </Tabs>
    <!-- 预览视图tab6 -->
    <Modal
      v-model="modal6"
      title="选手视角预览"
      footer-hide
      :width="1366"
      @on-cancel="cancelsmtModal6('formModal6')"
    >
      <!-- Display -->
      <div id="display" style="overflow: hidden;display: flex;justify-content:center;">
        <div style="background: red;"></div>
      </div>
    </Modal>
    <Modal v-model="screenPlaybackMd" title="回放" width="83%" footer-hide @on-cancel="cancelSPMD">
      <NoData :loading="recordLoading" v-if="recordLoading"></NoData>
      <!-- Guacamole recording player -->
      <div id="player" v-show="recordLoading === false">
        <!-- Player display -->
        <div id="display1">
          <div class="notification-container">
            <div class="seek-notification">
              <p>
                Seek in progress...
                <button id="cancel-seek">Cancel</button>
              </p>
            </div>
          </div>
        </div>

        <!-- Player controls -->
        <div class="controls">
          <button id="play-pause">播放</button>
          <button id="live">完成</button>
          <Select filterable name="speed" id="speed">
            <option value="1">1X</option>
            <option value="2">2X</option>
            <option value="5">5X</option>
          </select>
          <input id="position-slider" type="range" />
          <span id="position">00:00</span>
          <span>/</span>
          <span id="duration">00:00</span>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import Guacamole from '@/assets/minejs/all.min'
import {
  getaccessgrouplist,
  transcodingBySessionId,
  queryTranscodingStatus
} from '@/api/access_new'
import { debounce } from '@/libs/utils'
import {
  getSessions,
  getSessionsBydevice,
  pushNettingData,
  getSessionsRecord,
  getTranscodingStatus,
  sessionTranscoding,
  reportScreenPlayback,
  getScreenPlaybackPage
} from '@/api/drill'
import { getuserinstance } from '@/api/access_new'

export default {
  name: 'scenes',
  // isMainRange: 0 分靶场 1 主靶场
  props: ['type', 'poll', 'drillStatus', 'isDistributed', 'isMainRange'], //接受演练竞赛类型
  components: {},
  data() {
    return {
      routename: this.$route.name,
      currToken: '',
      screenPlaybackMd: false,
      currRecordId: '',
      tabName: this.poll === false ? 'name2' : 'name1',
      routeParams: {
        id: this.$route.query.id,
        prjid: this.$route.query.prjid || this.$route.query.projectId // 裁判详情页面用的 projectId 字段
      },
      vms4RedBlue: [],
      currPage: 1,
      currSize: 10,
      modal6: false,
      previewid: -9999,
      projectId: this.$route.query.prjid || this.$route.query.projectId,
      tab6TeamId: '',
      tab6move: false,
      guac: '',
      tab6TbData: [],
      tab6PageCount: 0,
      tab6TbTitle: [
        {
          title: '虚拟机名称',
          key: 'name',
          placement: 'top-left',
          width: 240,
          tooltip: true
        },
        {
          title: '团队名称',
          key: 'teamName',
          width: 120,
          filter: (temName, data) => {
            //userId永远对不上，列表里面是设计师的id，不知道为啥写这个，先这样吧
            let member = this.projectGroupMemberList.find((user) => user.userId == data.userId)
            return member ? member.accessGroupName : ''
          }
          // render: (h, params) => {
          // 	if(this.projectGroupMemberList.length > 0) {
          // 		let name = this.projectGroupMemberList.find(user => user.userId == params.row.userId)
          // 		return h('Tooltip',{
          // 			'class':'tableTooltip',
          // 			props:{
          // 				maxWidth:400,
          // 				placement:'top',
          // 				triggle:'hover',
          // 				transfer:true
          // 			}
          // 		},[
          // 			h('p',{
          // 				'class':'showContent',
          // 				style:{
          // 					maxWidth:'120px'
          // 				}
          // 			}, name),
          // 			h('div',{
          // 				'class':'tooltipContent',
          // 				slot:'content'
          // 			}, name)
          // 		])
          // 	} else {
          // 		return h('span', '')
          // 	}
          // }
        },
        {
          title: '昵称',
          key: 'userName',
          width: 120,
          tooltip: true
        },
        {
          title: '协议',
          key: 'protocol',
          width: 60
        },
        {
          title: 'IP',
          key: 'ip',
          width: 120
        },
        {
          title: '连接时间',
          key: 'connectTime'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 100,
          placement: 'top-right',
          action: true,
          opList: [
            {
              txt: '预览',
              on: {
                click: (data) => {
                  this.modal6 = true
                  this.previewid = data.id
                  this.guac = ''
                  document.getElementById('display').innerHTML = ''
                  this.preview(data)
                }
              }
            }
          ]
          // render: (h, params) => {
          // 	return h('div', [
          // 		h('Button', {
          // 			props: {
          // 				type: 'info',
          // 				size: 'small'
          // 			},
          // 			style: {
          // 				marginRight: '5px'
          // 			},
          // 			on: {
          // 				click: () => {
          // 					this.modal6 = true;
          // 					this.guac = '';
          // 					this.preview(params);
          // 				}
          // 			}
          // 		}, '预览'),
          //                                h('Button', {
          //                                    props: {type: 'info',size: 'small'},
          //                                    style: {marginRight: '5px'},
          //                                    on: {
          //                                        click: () => {
          //                                            this.macro = 0;
          //                                            this.changeView(params)
          //                                        }
          //                                    }
          //                                }, '选手视角直推'),
          //                                h('Button', {
          //                                    props: {type: 'info',size: 'small'},
          //                                    style: {marginRight: '5px'},
          //                                    on: {
          //                                        click: () => {
          //                                            this.macro = 1;
          //                                            this.changeView(params)
          //                                        }
          //                                    }
          //                                }, '宏观视角')
          // ]);
          // }
        }
      ],
      tab6TbTitle1: [
        {
          type: 'selection',
          width: 60,
          show: () => this.isReportButton
        },
        {
          title: '虚拟机名称',
          key: 'name',
          placement: 'top-left',
          width: 240,
          tooltip: true
        },
        {
          title: '团队名称',
          key: 'teamName',
          width: 120,
          filter: (temName, data) => {
            //userId永远对不上，列表里面是设计师的id，不知道为啥写这个，先这样吧
            let member = this.projectGroupMemberList.find((user) => user.userId == data.userId)
            return member ? member.accessGroupName : ''
          }
          // render: (h, params) => {
          // 	if(this.projectGroupMemberList.length > 0) {
          // 		let name = this.projectGroupMemberList.filter(user => user.userId == params.row.userId)[0].accessGroupName
          // 		return h('Tooltip',{
          // 			'class':'tableTooltip',
          // 			props:{
          // 				maxWidth:400,
          // 				placement:'top',
          // 				triggle:'hover',
          // 				transfer:true
          // 			}
          // 		},[
          // 			h('p',{
          // 				'class':'showContent',
          // 				style:{
          // 					maxWidth:'120px'
          // 				}
          // 			}, name),
          // 			h('div',{
          // 				'class':'tooltipContent',
          // 				slot:'content'
          // 			}, name)
          // 		])
          // 	} else {
          // 		return h('span', '')
          // 	}
          // }
        },
        {
          title: '昵称',
          key: 'userName',
          width: 120,
          tooltip: true
        },
        {
          title: '协议',
          key: 'protocol',
          width: 60
        },
        {
          title: 'IP',
          key: 'ip',
          width: 120
        },
        {
          title: '连接时间',
          key: 'connectTime'
        },
        {
          title: '断开时间',
          key: 'disconnectTime'
        },
        {
          title: '上报状态',
          key: 'uploadStatus',
          show: () => this.isReportButton,
          // filter: (uploadStatus,data) => {
          //     return uploadStatus == 0 ? '未上报':uploadStatus == 1 ? '上报中':uploadStatus == 2 ? '上报失败': '已完成'
          // },
          // setColor: (uploadStatus,data) => {
          //     return uploadStatus == 0 ? 'var(--status-no)':uploadStatus == 2 ? 'var(--status-no)': uploadStatus == 1 ? 'var(--status-ing)': 'var(--status-yes)'
          // },
          render: (h, params) => {
            let { uploadStatus } = params.row
            let color =
              uploadStatus == 0
                ? 'var(--status-no)'
                : uploadStatus == 2
                ? 'var(--status-no)'
                : uploadStatus == 1
                ? 'var(--status-ing)'
                : 'var(--status-yes)'
            let name =
              uploadStatus == 0
                ? '未上报'
                : uploadStatus == 1
                ? '上报中'
                : uploadStatus == 2
                ? '上报失败'
                : '已完成'
            return h(
              'Tag',
              {
                props: {
                  color: color
                }
              },
              name
            )
          }
        },
        {
          title: '转码状态',
          key: 'accessVideo',
          show: () => this.poll === false, //赛后
          filter: (accessVideo, data) => {
            let statusObj = this.transcodingStatusList.find((item) => item.sessionId === data.id)
            return statusObj ? this.filterTranscodingStatus(statusObj.status).txt : '未转码'
          },
          setColor: (accessVideo, data) => {
            let statusObj = this.transcodingStatusList.find((item) => item.sessionId === data.id)
            return statusObj ? this.filterTranscodingStatus(statusObj.status).color : '未转码'
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: this.poll === false ? 180 : 100,
          placement: 'top-right',
          action: true,
          opList: [
            {
              txt: '转码',
              tooltip: true,
              title: '将该录屏转码成MP4格式',
              show: () => this.poll === false, //赛后
              disabled: (data) => {
                let statusObj = this.transcodingStatusList.find(
                  (item) => item.sessionId === data.id
                )
                return statusObj
                  ? ['success', 'transcoding'].includes(statusObj.status)
                  : data.accessVideo
                  ? true
                  : false
              },
              fun: (data) => {
                this.transcodingBySessionId(data.id)
              }
            },
            {
              txt: '下载录屏',
              show: () => this.poll === false, //赛后
              disabled: (data) => (data.accessVideo ? false : true),
              fun: (data) => {
                this.downloadFile(data.accessVideo)
              }
            },
            {
              txt: '回放',
              on: {
                click: (data) => {
                  this.showRecordScreen(data)
                }
              }
            }
          ]
          // render: (h, params) => {
          // 	return h('div', [
          // 		h('Button', {
          // 			props: {
          // 				type: 'info',
          // 				size: 'small'
          // 			},
          // 			style: {
          // 				marginRight: '5px'
          // 			},
          // 			on: {
          // 				click: () => {
          // 					this.showRecordScreen(params);
          // 				}
          // 			}
          // 		}, '回放'),
          // 	]);
          // }
        }
      ],
      queryGroupMemberInfo: {
        testId: this.$route.query.id,
        pageIndex: 1,
        pageSize: 1000000
      },
      searchMemberlist: [], // 用于查询的下拉框数据要去重
      projectGroupMemberList: [],
      repeatTimeout: -1,
      recordLoading: false,
      transcodingStatus: '',
      accessGroupId: '',
      team2deviceMap: {},
      team2UserMap: {},
      deviceIds: [],
      userlist: [],
      connectTime: '',
      disconnectTime: '',
      selectSession: [], // 选则录屏数据
      hasData: false,
      transcodingStatusList: []
    }
  },
  filters: {},
  watch: {
    tabName(val) {
      this.tab6Change(1)
      if (val === 'name2') {
        // this.getTranscodingStatus();
      }
    },
    hasData(val) {
      // this.getTranscodingStatus();
    }
  },
  computed: {
    isReportButton() {
      return [0, 2, 7].includes(this.type) && this.isDistributed == 1 && this.isMainRange != 1
    }
  },
  beforeDestroy() {
    clearInterval(this.repeatTimeout)
  },
  mounted() {
    this.getAccessGroupList()
    this.getConnectAllHistories('init')
    this.getProjectGroupMember()
    // this.getTranscodingStatus();
    this.repeatTimeout = setInterval(() => {
      if (this.poll) {
        this.getConnectAllHistories()
      }
      if (
        this.hasData &&
        (this.transcodingStatusList.length === 0 ||
          this.transcodingStatusList.some((item) => item.status === 'transcoding'))
      ) {
        this.queryTranscodingStatus()
      }
    }, 5000)
  },
  methods: {
    filterTranscodingStatus(status) {
      let txt = '未转码',
        color = 'var(--staus-pre)'
      if (status === 'success') {
        color = 'var(--status-yes)'
        txt = '转码成功'
      } else if (status === 'failed') {
        color = 'var(--status-yes)'
        txt = '转码失败'
      } else if (status === 'transcoding') {
        color = 'var(--status-ing)'
        txt = '转码中'
      }
      return {
        color,
        txt
      }
    },
    transcodingBySessionId(id) {
      transcodingBySessionId(id)
        .then(({ code, success }) => {
          if (code === 1 && success) {
            this.$Message.info('操作成功')
          } else {
            this.$Message.error('操作失败')
          }
        })
        .catch((error) => {
          this.$Message.error('转码失败')
        })
    },
    queryTranscodingStatus() {
      let params = {
        pageIndex: 1,
        pageSize: 9999,
        projectId: this.projectId
      }
      queryTranscodingStatus(params)
        .then(({ code, data }) => {
          if (code === 1) {
            this.transcodingStatusList = data.items
            if (this.transcodingStatusList.some((item) => item.status === 'failed')) {
              this.transcodingStatus = 'failed'
            } else if (this.transcodingStatusList.some((item) => item.status === 'transcoding')) {
              this.transcodingStatus = 'transcoding'
            } else if (
              this.tab6PageCount === this.transcodingStatusList.length &&
              this.transcodingStatusList.every((item) => item.status === 'success')
            ) {
              this.transcodingStatus = 'success'
            } else {
              this.transcodingStatus = ''
            }
          } else {
            this.transcodingStatusList = []
          }
        })
        .catch((error) => {
          this.transcodingStatusList = []
        })
    },
    reportScreenRecording() {
      if (this.selectSession.length == 0) {
        this.$Message.warning('请选择上报录屏数据')
        return
      }
      let ids = []
      ids = this.selectSession.map((item) => item.id)
      reportScreenPlayback(ids, this.$route.query.id)
        .then((res) => {
          if (res.code === 1) {
            this.getConnectAllHistories()
            this.selectSession = []
            this.$Message.info('操作成功')
          } else {
            this.$Message.warning(res.message)
          }
        })
        .catch((error) => {
          this.$Message.error('上报失败')
        })
    },
    sessionTranscoding() {
      sessionTranscoding(this.projectId)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.$Message.info('操作成功')
            // this.getTranscodingStatus()
          } else {
            this.$Message.error(message)
          }
        })
        .catch((error) => {
          this.$Message.error('转码失败')
        })
    },
    // getTranscodingStatus(){
    // 	if(!this.hasData){
    // 		return
    // 	}
    // 	getTranscodingStatus(this.projectId).then(({code,data,message}) => {
    // 		if(code === 1){
    // 			this.transcodingStatus = data ? data.status : '';
    // 			if(this.transcodingStatus === 'transcoding'){
    // 				setTimeout(() => {
    // 					this.getTranscodingStatus()
    // 				},5000)
    // 			}
    // 		}else{
    // 			this.$Message.error(message)
    // 		}
    // 	}).catch(error => {
    // 		this.$Message.error('获取转码状态失败')
    // 	})
    // },
    cancelSPMD() {
      let display = document.getElementById('display1')
      this.recording.pause()
      let childs = display.childNodes
      for (let i = childs.length - 1; i >= 0; i--) {
        if (childs[i].className == 'notification-container') {
          return
        } else {
          display.removeChild(childs[i])
        }
      }
    },
    showRecordScreen(data) {
      this.recordLoading = true
      this.screenPlaybackMd = true
      getSessionsRecord(data.id)
        .then((res) => {
          // 查看是否可以下载回放并播放
          if (res.code !== undefined && res.code !== 1) {
            this.$Message.warning(res.message)
            this.recordLoading = false
            return
          }
          this.recordLoading = false
          this.currToken = data.token
          this.currRecordId = data.id
          this.initPlayer()
        })
        .catch((error) => {
          this.recordLoading = false
        })
    },
    cancelsmtModal6(name) {
      this.modal6 = false
      // let display = document.getElementById("display");
      // this.guac.disconnect();
      // display.innerHTML = "";
    },
    handleClose(vm) {
      //移除保存数据
      this.vms4RedBlue.splice(
        this.vms4RedBlue.findIndex((item) => item.vmId === vm.vmId),
        1
      )
    },
    changeTeam(val) {
      // 根据团队id， 获取设备id列表， 根据  List<string> deviceIds 查询 列表
      console.log('当前团队', val)
      if (val) {
        let devices = this.team2deviceMap[val] || []
        this.deviceIds = devices.map((item) => {
          return item.deviceId
        })
        this.userlist = this.team2UserMap[val] || []
      } else {
        this.deviceIds = [] // 如果团队为空，设备列表也为空
      }
      console.log('查询团队的 设备列表', this.deviceIds)
      this.currPage = 1
      this.getConnectAllHistories()
    },
    clickOkBtn() {
      this.getConnectAllHistories()
    },
    clickClearBtn() {
      this.changeDates()
      this.clickOkBtn()
    },
    changeDates(time) {
      this.connectTime = time || ''
    },
    clickOkDisconnect() {
      this.getConnectAllHistories()
    },
    clickClearDisconnect() {
      this.changeDisconnect()
      this.clickOkDisconnect()
    },
    changeDisconnect(time) {
      this.disconnectTime = time || ''
    },
    tab6Change(page) {
      this.currPage = page
      this.getConnectAllHistories()
    },
    getConnectAllHistories(type) {
      let methodfun = getSessions
      // let methodfun = getScreenPlaybackPage
      let _this = this
      let params = {}
      if (!_this.tab6TeamId) {
        params = {
          pageIndex: _this.currPage,
          pageSize: _this.currSize,
          status: this.tabName === 'name1' ? 'connected' : 'disconnected',
          userType: 'experimenter',
          projectId: _this.projectId,
          enableRecordScreen: true,
          sceneId: this.$route.query.id || this.$route.query.sceneId
        }
        let routename = this.routename
        if (
          [1, 9, 2].includes(_this.type) ||
          routename == 'awdContestDetail' ||
          routename == 'opContestDetail'
        ) {
          // 夺旗赛2，1，9运维赛、攻防赛
          if (_this.deviceIds && this.deviceIds.length > 0) {
            // params.teamId = _this.accessGroupId // 接口无法根据团队来查询，只能根据设备来查询
            params.deviceIds = _this.deviceIds
            params.userIds = _this.userlist

            // console.log('团队的设备啊啊啊--------',params.deviceIds,params.userIds)

            methodfun = getSessionsBydevice
          }
          if (_this.connectTime) {
            params.connectTime = _this.connectTime
          }
          if (_this.disconnectTime) {
            params.disconnectTime = _this.disconnectTime
          }
        }
        // if([0,2,7].includes(this.type) && this.isDistributed == 1){
        // 	methodfun = getScreenPlaybackPage
        // }
      } else {
        params = {
          pageIndex: _this.currPage,
          pageSize: _this.currSize,
          status: this.tabName === 'name1' ? 'connected' : 'disconnected',
          userType: 'experimenter',
          // teamId: _this.tab6TeamId,
          // accessGroupId: _this.tab6TeamId,
          projectId: _this.projectId,
          enableRecordScreen: true,
          enableRecordScreenPlayback: true,
          sceneId: this.$route.query.id || this.$route.query.sceneId
        }
      }

      let query = {
        pageIndex: params.currPage,
        pageSize: params.currSize
      }

      // 实时录屏还是使用原来接口
      if (this.tabName == 'name1') {
        methodfun = getSessions
      }

      // methodfun(params).then(data => {
      methodfun(params).then((data) => {
        if (data.code == 1) {
          data.data.items.map((item) => {
            if (typeof item.teamName == 'undefined') {
              item.teamName = '-'
            }
          })
          _this.tab6TbData = data.data.items
          _this.tab6PageCount = data.data.total
          if (type === 'init') {
            //初始化查询存储是否有数据
            _this.hasData = _this.tab6TbData.length > 0 ? true : false
            if (_this.hasData) {
              this.queryTranscodingStatus()
            }
          }
          let haspreviewid = _this.tab6TbData.some(function(element) {
            return element.id === _this.previewid
          })

          if (!haspreviewid && _this.modal6) {
            // 如果列表中没有预览的id 则关闭预览框
            _this.$Message.warning('实验员已断开接入')
            _this.modal6 = false
          }
        } else {
        }
      })
    },

    // 简单获取团队列表
    getAccessGroupList() {
      if (!this.routeParams.id) {
        return
      }
      let params = this.queryGroupMemberInfo
      this.searchMemberlist = []
      getaccessgrouplist(params).then((data) => {
        if (data.code == 1) {
          // 夺旗赛过滤掉spare1组
          let items = data.data.items || []
          this.searchMemberlist = items.filter((item) => !item.spare)
        } else if (data.code == -2) {
          this.searchMemberlist = []
        } else {
          this.$Message.warning(data.message)
        }
      })
    },

    // 获取所有的团队，及对应的信息
    getProjectGroupMember() {
      if (!this.queryGroupMemberInfo.testId) {
        this.queryGroupMemberInfo.testId = this.$route.query.id || this.$route.query.sceneId //公用页面，有时候是 id,有时候是sceneId
      }
      let team2deviceMap = {} // 团队id 和 设备列表的 map
      let team2UserMap = {}
      getuserinstance(this.queryGroupMemberInfo).then((data) => {
        if (data.code == 1) {
          let projectGroupMemberList = data.data.items.filter(
            (item) => item.inviterName != '内部服务用户'
          )

          let alllist = JSON.parse(JSON.stringify(projectGroupMemberList))
          alllist.forEach((item) => {
            let teamid = item.accessGroupId
            let deviceList = team2deviceMap[teamid] || []
            team2deviceMap[teamid] = deviceList.concat(item.deviceList)

            let userlist = team2UserMap[teamid] || []
            team2UserMap[teamid] = userlist.concat(item.userId)
          })
          this.team2deviceMap = team2deviceMap
          this.team2UserMap = team2UserMap

          // console.log('团队和设备的列表啊啊啊啊最原始的数据啊啊啊-------',data.data.items,team2UserMap)

          const filteredData = Array.from(
            new Set(projectGroupMemberList.map((item) => item.accessGroupId))
          ).map((accessGroupId) =>
            projectGroupMemberList.find((item) => item.accessGroupId === accessGroupId)
          ) // 去重

          //this.searchMemberlist = filteredData
          this.projectGroupMemberList = projectGroupMemberList
          console.log('this.projectGroupMemberList', this.projectGroupMemberList, team2deviceMap)
        } else if (data.code == -2) {
          this.projectGroupMemberList = []
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    initPlayer() {
      /**
       * The URL of the Guacamole session recording which should be played back.
       *
       * @constant
       * @type String
       */

      var token = this.currToken //this.GetQueryString("token");
      // var token = "02f3a158b81347dba1526d485389c614";
      document.cookie = 'token=' + token
      if (!token) {
        //alert('文件为空');
        this.$Message.error('文件为空')
        this.screenPlaybackMd = false
        return
      }
      // let crheetian = "http://172.18.100.4/api/"
      let crheetian = '/api/'
      // console.log(token)
      var param = 'token=' + token
      var RECORDING_URL = crheetian + 'access/sessions/' + this.currRecordId + '/recording'

      /**
       * The element representing the session recording player.
       *
       * @type Element
       */
      var player = document.getElementById('player')

      /**
       * The element which will contain the recording display.
       *
       * @type Element
       */
      var display = document.getElementById('display1')

      /**
       * Play/pause toggle button.
       *
       * @type Element
       */
      var playPause = document.getElementById('play-pause')
      // playPause.trigger('click');

      var live = document.getElementById('live')
      var speed = document.getElementById('speed')
      speed.value = 1
      /**
       * Button for cancelling in-progress seek operations.
       *
       * @type Element
       */
      var cancelSeek = document.getElementById('cancel-seek')

      /**
       * Text status display indicating the current playback position within the
       * recording.
       *
       * @type Element
       */
      var position = document.getElementById('position')

      /**
       * Slider indicating the current playback position within the recording,
       * and allowing the user to change the playback position.
       *
       * @type Element
       */
      var positionSlider = document.getElementById('position-slider')

      /**
       * Text status display indicating the current length of the recording.
       *
       * @type Element
       */
      var duration = document.getElementById('duration')

      /**
       * The tunnel which should be used to download the Guacamole session
       * recording.
       *
       * @type Guacamole.Tunnel
       */
      var tunnel = new Guacamole.StaticHTTPTunnel(RECORDING_URL)
      //var tunnel = new Guacamole.WebSocketTunnel(RECORDING_URL);

      /**
       * Guacamole.SessionRecording instance to be used to playback the session
       * recording.
       *
       * @type Guacamole.SessionRecording
       */
      var recording = new Guacamole.SessionRecording(tunnel)
      this.recording = recording
      /**
       * The Guacamole.Display which displays the recording during playback.
       *
       * @type Guacamole.Display
       */
      var recordingDisplay = recording.getDisplay()

      /**
       * Converts the given number to a string, adding leading zeroes as necessary
       * to reach a specific minimum length.
       *
       * @param {Numer} num
       *     The number to convert to a string.
       *
       * @param {Number} minLength
       *     The minimum length of the resulting string, in characters.
       *
       * @returns {String}
       *     A string representation of the given number, with leading zeroes
       *     added as necessary to reach the specified minimum length.
       */
      var zeroPad = function zeroPad(num, minLength) {
        // Convert provided number to string
        var str = num.toString()

        // Add leading zeroes until string is long enough
        while (str.length < minLength) str = '0' + str

        return str
      }

      /**
       * Converts the given millisecond timestamp into a human-readable string in
       * MM:SS format.
       *
       * @param {Number} millis
       *     An arbitrary timestamp, in milliseconds.
       *
       * @returns {String}
       *     A human-readable string representation of the given timestamp, in
       *     MM:SS format.
       */
      var formatTime = function formatTime(millis) {
        // Calculate total number of whole seconds
        var totalSeconds = Math.floor(millis / 1000)

        // Split into seconds and minutes
        var seconds = totalSeconds % 60
        var minutes = Math.floor(totalSeconds / 60)

        // Format seconds and minutes as MM:SS
        return zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2)
      }
      // console.log(recordingDisplay, 1111)
      // Add playback display to DOM
      display.appendChild(recordingDisplay.getElement())

      // Begin downloading the recording
      console.log(param)
      recording.connect(param)

      // If playing, the play/pause button should read "Pause"
      let btnTimer = null
      playPause.textContent = '暂停'
      var flag = false
      recording.onplay = debounce(function() {
        // console.log('触发播放', speed,recording.isPlaying())
        if (recording.isPlaying()) {
          playPause.textContent = '暂停'
        }
        // clearTimeout(btnTimer);
        // playPause.textContent = '暂停';
        // btnTimer = setTimeout(function(){
        // 	if( playPause.textContent == '播放'){
        // 		return
        // 	}
        // },500)
      }, 500)
      // If paused, the play/pause button should read "Play"
      recording.onpause = debounce(function() {
        // console.log('触发暂停', speed,recording.isPlaying(),flag)
        if (!recording.isPlaying()) {
          playPause.textContent = '播放'
        }
      }, 500)
      // Toggle play/pause when display or button are clicked
      let timer
      function dd_seek() {
        timer && clearTimeout(timer)
        let max = recording.getDuration()
        let current = recording.getPosition()
        if (current >= max) {
          timer = null
          return
        }
        // console.log('dd_seek',current)
        recording.seek(current + 100, function() {
          player.className = ''
          switch (speed.value) {
            case '2':
              timer = setTimeout(dd_seek, 300)
              break //25 5倍  100 2倍
            case '5':
              timer = setTimeout(dd_seek, 120)
              break //25 5倍（速度过快修改为50）  100 2倍
          }
        })
      }

      // Toggle play/pause when display or button are clicked
      display.onclick = playPause.onclick = function() {
        flag = !flag
        if (!recording.isPlaying()) {
          playPause.textContent = '暂停'
          recording.play()
          let max = recording.getDuration()
          let current = recording.getPosition()
          console.log(`max:${max},current:${current}`)
          if (current >= max) {
            recording.seek(current - current, function() {
              speed.value = 1
              recording.play()
            })
            // return;
          }
          if (speed.value == '1') {
            clearTimeout(timer)
            timer = null
          } else {
            dd_seek()
          }
        } else {
          playPause.textContent = '播放'
          recording.pause()
          if (timer) {
            clearTimeout(timer)
            timer = null
          }
        }
      }

      // display.onclick = playPause.onclick = function () {
      //     if (!recording.isPlaying())
      //         recording.play();
      //     else
      //         recording.pause();
      // };

      // Resume playback when cancel button is clicked
      cancelSeek.onclick = function cancelSeekOperation(e) {
        recording.play()
        player.className = ''
        e.stopPropagation()
      }

      // Fit display within containing div
      recordingDisplay.onresize = function displayResized(width, height) {
        // Do not scale if display has no width
        if (!width) return

        // Scale display to fit width of container
        recordingDisplay.scale(display.offsetWidth / width)
      }
      let sliderPos = 0
      // Update slider and status when playback position changes
      recording.onseek = function positionChanged(millis) {
        position.textContent = formatTime(millis)
        positionSlider.value = sliderPos ? sliderPos : millis
      }

      // 在五秒内计算如果时常没有变化就跳转到最后的时间

      // Update slider and status when duration changes
      recording.onprogress = function durationChanged(millis) {
        duration.textContent = formatTime(millis)
        positionSlider.max = millis
        //console.log('获取到新消息');
        if (!recording.isPlaying()) {
          //console.log('获取到新消息，继续播放')
          recording.play()
        }
      }
      positionSlider.onclick = function aaa(e) {
        // recording.pause();
        sliderPos = (e.offsetX * positionSlider.max) / e.currentTarget.clientWidth

        if (speed.value != '1') {
          clearTimeout(timer)
          timer = null
        }
        recording.seek(sliderPos, function seekComplete() {
          // Seek has completed
          positionSlider.value = sliderPos
          sliderPos = 0
          player.className = ''
          // recording.play()
          if (speed.value != '1') {
            dd_seek()
          }
        })
      }
      // // Seek within recording if slider is moved
      // positionSlider.onchange = function sliderPositionChanged() {

      // 	console.log(positionSlider.value);
      // 	// Request seek
      // 	recording.seek(positionSlider.value, function seekComplete() {

      // 		// Seek has completed
      // 		player.className = '';

      // 	});

      // 	// Seek is in progress
      // 	player.className = 'seeking';

      // };

      live.onclick = function() {
        // Request seek
        recording.seek(positionSlider.max, function seekComplete() {
          // Seek has completed
          player.className = ''
        })

        // Seek is in progress
        player.className = 'seeking'
      }
      speed.onchange = function(e) {
        clearTimeout(timer)
        clearTimeout(btnTimer)
        timer = null
        if (speed.value != '1') {
          dd_seek()
        }
      }
    },
    preview(data) {
      // var webURL = 'ws://172.18.0.22:18766/tunnel/webSocket';
      var webURL = '/api/access/tunnel/webSocket'
      // Get display div from document
      let display = document.getElementById('display')

      // Instantiate client, using an HTTP tunnel for communications.
      // If WebSocket available, try to use it.
      //let guac ='';
      if (!!window.WebSocket && window.WebSocket.prototype.send) {
        var tunnel = new Guacamole.WebSocketTunnel(webURL)
      } else {
        // If no WebSocket, then use HTTP.
        // tunnel = new Guacamole.HTTPTunnel('tunnel');
        alert('非常抱歉，您的浏览器不支持WebSocket，请安装最新谷歌浏览器再试。')
        // return;
      }
      this.guac = new Guacamole.Client(tunnel)

      // Add client to display div
      // var childs = display.childNodes;
      // for(var i = childs.length - 1; i >= 0; i--) {
      //     display.removeChild(childs[i]);
      // }

      display.appendChild(this.guac.getDisplay().getElement())
      // 设置缩放比例
      if (data.width > 1300) {
        // 大于1300 缩放到1300
        this.guac.getDisplay().scale(1300 / data.width) //缩放，滚动条
        // data.width 为录屏返回的宽度， 传过去的是看这个页面的宽度（和弹窗保持大小）---测试
        var width = 1300 //data.width; //localStorage.vncWidth;
        var height = data.height * (1300 / data.width) //localStorage.vncHeight;
      } else {
        // 小于1300 不缩放
        // this.guac.getDisplay().scale(1300 / 1600); //不缩放，滚动条
        // data.width 为录屏返回的宽度， 传过去的是看这个页面的宽度（和弹窗保持大小）---测试
        var width = data.width //localStorage.vncWidth;
        var height = data.height //localStorage.vncHeight;
      }

      // Error handler
      this.guac.onerror = function(error) {
        console.log('this.guac.onerror', error)
      }
      // token改为recordId,recordId接口查,取第一个的id(状态)

      var recordId = data.id //localStorage.recordId;
      var token = data.token
      // Connect
      var paramStr =
        'sessionId=' +
        recordId +
        '&maxWidth=1300' +
        '&width=' +
        width +
        '&height=' +
        height +
        '&observer=true'
      console.log(paramStr)
      this.guac.connect(paramStr)

      // Disconnect on close
      window.onunload = function() {
        this.guac.disconnect()
      }
    },
    changeView(params) {
      let _this = this
      let paras = {}
      paras.dname = params.row.instanceName
      paras.dacc = params.row.id
      paras.macro = _this.macro
      paras.type = 'switchCamera'
      paras.vmId = params.row.vmId
      paras.width = params.row.width
      paras.height = params.row.height
      paras.teamName = params.row.teamName
      paras.userName = params.row.userName
      paras.connectTime = params.row.connectTime
      paras.vmName = params.row.name
      let action = []
      if (_this.tab6move) {
        action.push('move')
        action.push('screen')
      } else {
        action.push('screen')
      }
      paras.action = action
      if (_this.macro == 0) {
        if (_this.vms4RedBlue.length == 2) {
          _this.vms4RedBlue[0] = _this.vms4RedBlue[1]
          _this.vms4RedBlue.splice(1, 1)
          //console.log(JSON.stringify(_this.vms4RedBlue))
        }
        _this.vms4RedBlue.push(paras)
      } else if (_this.macro == 1) {
        _this.vms4RedBlue = []
      }
      console.log(JSON.stringify(paras))
      paras.projectId = _this.projectId

      pushNettingData(paras).then((data) => {
        if (data.code != '1') {
          _this.$Message.warning(data.message)
        } else {
          _this.$Message.info('操作成功')
        }
      })
    },
    getTeams() {
      let _this = this
      axios({
        url: 'director/attack/teams?projectId=' + _this.nowUsePrjId,
        method: 'get'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.warning(response.message)
        } else {
          _this.tab7TbData = response.data
        }
      })
    },
    downloadFile(filePath) {
      const downloadElement = document.createElement('a')
      downloadElement.href = filePath
      // downloadElement.download = `${fileName}.xlsx`;
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    }
  }
}
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}

.scenesHeader {
  margin-bottom: 16px;
}

.drillTables {
  min-height: 300px;
}

.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
#display /deep/ > div:first-child {
  max-width: 100% !important;
  min-height: 300px !important;
  min-width: 400px;
}

#display1 {
  position: relative;
}
#player .notification-container {
  position: absolute;
  z-index: 1;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

#player .seek-notification {
  color: white;
  background: rgba(0, 0, 0, 0.75);

  display: none; /* Initially hidden */
  width: 100%;
  height: 100%;
}

#player.seeking .seek-notification {
  display: table;
}

#player .seek-notification p {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  font-family: sans-serif;
}

#player .controls {
  width: 100%;

  /* IE10 */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-direction: row;

  /* Ancient Mozilla */
  display: -moz-box;
  -moz-box-align: center;
  -moz-box-orient: horizontal;

  /* Ancient WebKit */
  display: -webkit-box;
  -webkit-box-align: center;
  -webkit-box-orient: horizontal;

  /* Old WebKit */
  display: -webkit-flex;
  -webkit-align-items: center;
  -webkit-flex-direction: row;

  /* W3C */
  display: flex;
  align-items: center;
  flex-direction: row;
}

#player .controls > * {
  margin: 0.25em;
}

#player .controls #position-slider {
  -ms-flex: 1 1 auto;
  -moz-box-flex: 1;
  -webkit-box-flex: 1;
  -webkit-flex: 1 1 auto;
  flex: 1 1 auto;
}

#player .controls #play-pause,
#player .controls #live {
  margin-left: 0;
  min-width: 5em;
}

#player .controls #position,
#player .controls #duration {
  font-family: monospace;
}

#player .controls #duration {
  margin-right: 0;
}
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}

.targetHeader {
  /*padding: 10px;*/
  margin-bottom: 10px;
}
</style>
